<?php

/**
 * Class UserManager
 */
class UserManager
{
    /**
     * @param $email
     * @param $password
     * @return User
     * @throws FormatException
     * @throws AlreadyExistException
     * @throws DatabaseException
     */
    public static function register($email, $password)
    {
        /** @var $CI CI */
        $CI =& get_instance();
        $CI->load->helper('email');
        $CI->load->helper('security');

        //判断邮箱是否合法
        if (!valid_email($email)) {
            throw new FormatException('不是合法的邮箱地址');
        }

        //判断邮箱是否已被使用
        if (self::isEmailExist($email)) {
            throw new AlreadyExistException('邮箱已被使用');
        }

        $salt = sprintf('%05d', rand(0, 99999));

        $thatUser = new User;
        $thatUser->setEmail($email);
        $thatUser->setSalt($salt);
        $thatUser->setPassword(do_hash(do_hash($password) . $salt));
        $thatUser->setPower(0);
        $thatUser->setRegIp($CI->input->ip_address());
        $thatUser->setRegTime(date("Y-m-d H:i:s", time()));

        return User_Model::add($thatUser);
    }

    /**
     * @param $email
     * @param $password
     * @throws NotExistException
     * @throws NotMatchException
     * @throws DatabaseException
     * @return User
     * @param $loginType 0为正常登录，1为微博登录
     */
    public static function login($email, $password, $loginType = '0')
    {
        /** @var $CI CI */
        $CI =& get_instance();
        $CI->load->helper('security');

        //判断邮箱是否存在
        if (!self::isEmailExist($email)) {
            throw new NotExistException('Email地址不存在');
        }

        //通过用户名获取用户
        $thatUser = User_Model::getUserByEmail($email);

        if ($thatUser->getSalt() == '#MD5#') {
            //检查密码是否正确
            if ($thatUser->getPassword() !== do_hash($password, 'md5')) {
                throw new NotMatchException('密码不匹配');
            }
            $salt = sprintf('%05d', rand(0, 99999));
            $thatUser->setSalt($salt);
            $thatUser->setPassword(do_hash(do_hash($password) . $salt));
        } else {
            if ($loginType === '0') {
                //检查密码是否正确
                if ($thatUser->getPassword() !== do_hash(do_hash($password) . $thatUser->getSalt())) {
                    throw new NotMatchException('密码不匹配');
                }
            } elseif ($loginType === '1') {
                if ($thatUser->getPassword() !== $password)
                    throw new NotMatchException('密码不匹配');
            }
        }

        //更新用户信息
        $thatUser->setLoginIp($CI->input->ip_address());
        $thatUser->setLoginTime(date("Y-m-d H:i:s", time()));
        $thatUser->setActIp($CI->input->ip_address());
        $thatUser->setActTime(date("Y-m-d H:i:s", time()));

        //更新数据库
        $thatUser = User_Model::update($thatUser);

        //储存用户ID信息至Session
        $CI->session->set_userdata('UserID', $thatUser->getID());

        return $thatUser;
    }

    /**
     *
     */
    public static function logout()
    {
        /** @var $CI CI */
        $CI =& get_instance();

        $CI->session->unset_userdata('UserID');
    }

    /**
     * @param User $thatUser
     * @param String $newPassword
     * @throws DatabaseException
     * @return User $thatUser
     */
    public static function changePassword($thatUser, $newPassword)
    {
        /** @var $CI CI */
        $CI =& get_instance();
        $CI->load->helper('security');

        $thatUser->setPassword(do_hash(do_hash($newPassword) . $thatUser->getSalt()));
        return User_Model::update($thatUser);
    }

    /**
     * @return User
     * @throws DatabaseException
     */
    public static function getCurrentUserBySession()
    {
        /** @var $CI CI */
        $CI =& get_instance();

        $id = $CI->session->userdata('UserID');

        //检查Session中的Token信息
        if (!$id || !is_numeric($id)) {
            //不存在或不合法
            self::logout();
            return new User();
        }

        //获取用户信息
        $thatUser = User_Model::getUserByID($CI->session->userdata('UserID'));

        //检查是否获取成功
        if (!$thatUser || $thatUser->getID() == 0) {
            //获取失败
            self::logout();
            return new User();
        }

        //更新用户活动时间
        $thatUser->setActIp($CI->input->ip_address());
        $thatUser->setActTime(date("Y-m-d H:i:s", time()));

        //更新数据库
        $thatUser = User_Model::update($thatUser);

        return $thatUser;
    }

    /**
     * @param string $email
     * @return bool
     */
    public static function isEmailExist($email)
    {
        if (User_Model::getUserByEmail($email)) {
            return true;
        } else {
            return false;
        }
    }

}